import { errorN, successM, warnN } from '@/utils/noticeUtil'

export const tableUtil = {
  data() {
    return {
      list: undefined, // 表格数据
      total: 0, // 数据总数
      listLoading: true, // 表格加载
      dialogFormVisible: false, // 添加或修改对话框是否显示
      dialogStatus: '', // 控制添加或修改对话框添加还是修改的属性
      textMap: { // 添加或修改对话框不同状态的文本
        update: '编辑',
        create: '添加'
      },
      deleteArrData: [] // 批量删除id数组
    }
  },
  methods: {
    reset() { // 重置数据
      let obj = this.param
      for (let key in obj) {
        if (key == 'current') {
          obj[key] = 1
        }
        if (key == 'pageSize') {
          obj[key] = 5
        } else {
          obj[key] = undefined
        }
      }
      this.param = obj
      this.getList()
    },
    handleFilter() { // 点击搜索和回车触发事件
      this.param.current = 1
      this.getList()
    },
    handleSaveData(row) { // 添加或者修改保存数据
      this.form = Object.assign({}, row)
      this.dialogStatus = JSON.stringify(row) === '{}' ? 'create' : 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    submitForm(saveData) { // 提交添加或修改数据
      let that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveData(that.form).then(res => {
            successM(this.textMap[this.dialogStatus] + '成功')
            that.dialogFormVisible = false
            that.getList()
          })
        }
      })
    },
    handleSelectionChange(val) { // 监听第一列选择变化
      if (val && val.length > 0) {
        let arr = []
        for (let index in val) {
          arr.push(val[index].id)
        }
        this.deleteArrData = arr
      }
    },
    tableBatchDelete(batchDelete) { // 批量删除数据
      if (this.deleteArrData && this.deleteArrData.length <= 0) {
        warnN('请先选择需要删除的数据!')
        return
      }
      batchDelete(this.deleteArrData).then(res => {
        this.getList()
        successM('删除成功')
        this.deleteArrData = []
      })
    },
    handleDelete(row, batchDelete) { // 单列删除
      this.deleteArrData.push(row.id)
      this.tableBatchDelete(batchDelete)
    },
    beforeImageUpload(file) { // 监听文件上传之前
      const isJPEG = file.type === 'image/jpeg'
      const isJPG = file.type === 'image/jpg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isJPG && !isJPEG && !isPNG) {
        errorN('上传头像图片只能是JPG或PNG或JPEG格式!')
        return false
      }
      if (!isLt2M) {
        errorN('上传头像图片大小不能超过 5MB!')
        return false
      }
      return true
    },
    handleAvatarSuccess(res, file) {
      this.$refs['upload'].clearFiles() //上传成功之后清除历史记录
      this.getList()  //初始化表格数据
    }
  }
}
